package elitech.vietnam.myfashion.dialog;

import java.io.IOException;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParserException;

import android.app.Dialog;
import android.os.AsyncTask;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import elitech.vietnam.myfashion.MainActivity;
import elitech.vietnam.myfashion.R;
import elitech.vietnam.myfashion.doinbackground.CallServiceTask;
import elitech.vietnam.myfashion.entites.City;
import elitech.vietnam.myfashion.entites.District;
import elitech.vietnam.myfashion.entites.Order;
import elitech.vietnam.myfashion.entites.OrderDetail;
import elitech.vietnam.myfashion.entites.Product;
import elitech.vietnam.myfashion.wsclient.Utilities;

public class ShippingDialog extends Dialog implements
		android.view.View.OnClickListener {

	private MainActivity mContext;
	private Dialog mDialog;

	private Button mBtnContinue, mBtnCancel;
	private EditText mTxtAddress, mTxtPhone, mTxtMemo;
	private TextView mTxtWarn, mTxtShipping;
	private Spinner mSpinCity, mSpinDistrict;
	private ArrayList<String> mCityListString = new ArrayList<String>();
	private ArrayList<String> mDistrictListString = new ArrayList<String>();
	private ArrayList<District> mDistrictListTemp = new ArrayList<District>();
	private ArrayAdapter<String> mCityAdapter, mDistrictAdapter;
	private int mCityLastPost, mDistrictLastPost;
	private boolean isBuyNow = false;

	public ShippingDialog(MainActivity context, boolean isBuyNow) {
		super(context, R.style.Dialog);
		this.mDialog = this;
		this.isBuyNow = isBuyNow;
		this.mContext = context;
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

		setContentView(R.layout.shipping);
		mTxtAddress = (EditText) findViewById(R.id.ship_txtAddress);
		mSpinCity = (Spinner) findViewById(R.id.ship_spinnerCity);
		mSpinDistrict = (Spinner) findViewById(R.id.ship_spinnerDistrict);
		mTxtPhone = (EditText) findViewById(R.id.ship_txtPhone);
		mTxtWarn = (TextView) findViewById(R.id.ship_txtWarn);
		mTxtShipping = (TextView) findViewById(R.id.ship_txtShippingFee);
		mTxtMemo = (EditText) findViewById(R.id.ship_txtMemo);

		mBtnContinue = (Button) findViewById(R.id.ship_btnContinue);
		mBtnCancel = (Button) findViewById(R.id.ship_btnCancel);

		mCityAdapter = new ArrayAdapter<String>(mContext,
				android.R.layout.simple_spinner_item, mCityListString);
		mCityAdapter
				.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		mSpinCity.setAdapter(mCityAdapter);

		mDistrictAdapter = new ArrayAdapter<String>(mContext,
				android.R.layout.simple_spinner_item, mDistrictListString);
		mDistrictAdapter
				.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		mSpinDistrict.setAdapter(mDistrictAdapter);

		mTxtAddress.setText(mContext.GetPreference("Address"));
		mTxtPhone.setText(mContext.GetPreference("Phone"));
		mCityLastPost = mContext.GetPreferenceInt("City");
		mDistrictLastPost = mContext.GetPreferenceInt("District");

		if (mContext.mListDistrict.size() == 0) {
			GetListDistrict();
		}

		if (mContext.mListCity.size() == 0) {
			GetListCity();
		} else {
			ListCityToListString();
		}

		mBtnContinue.setOnClickListener(this);
		mBtnCancel.setOnClickListener(this);

		mSpinCity.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				ListDistrictToListString(mContext.mListCity.get(pos).Id);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});

		mSpinDistrict.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				mTxtShipping.setText(Utilities.numberFormat(mDistrictListTemp
						.get(mSpinDistrict.getSelectedItemPosition()).Ship)
						+ " VNĐ");
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});

	}

	private void ListCityToListString() {
		for (City city : mContext.mListCity) {
			mCityListString.add(city.Name);
		}
		mCityAdapter.notifyDataSetChanged();
		if (mCityLastPost < mCityListString.size())
			mSpinCity.setSelection(mCityLastPost);
	}

	private void ListDistrictToListString(int IdCity) {
		mDistrictListString.clear();
		mDistrictListTemp.clear();
		for (District district : mContext.mListDistrict) {
			if (district.Publish == IdCity) {
				mDistrictListString.add(district.Name);
				mDistrictListTemp.add(district);
			}
		}
		mDistrictAdapter.notifyDataSetChanged();
		if (IdCity == mContext.mListCity.get(mCityLastPost).Id
				&& mDistrictLastPost < mCityListString.size())
			mSpinDistrict.setSelection(mDistrictLastPost);
		else
			mSpinDistrict.setSelection(0);
		mTxtShipping.setText(Utilities.numberFormat(mDistrictListTemp
				.get(mSpinDistrict.getSelectedItemPosition()).Ship) + " VNĐ");
	}

	public void GetListCity() {
		new CallServiceTask() {
			protected void onPreExecute() {
				mContext.mLoadingDialog.show();
			};

			private ArrayList<City> rs = new ArrayList<City>();

			public void work() {
				try {
					rs = service.getListCity();
				} catch (IOException e) {
				} catch (XmlPullParserException e) {
				}
			};

			protected void onPostExecute(Void result) {
				mContext.mListCity.addAll(rs);
				ListCityToListString();
				mContext.mLoadingDialog.dismiss();
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		;
	}

	public void GetListDistrict() {
		new CallServiceTask() {
			private ArrayList<District> rs = new ArrayList<District>();

			public void work() {
				try {
					rs = service.getListDistrict();
				} catch (IOException e) {
				} catch (XmlPullParserException e) {
				}
			};

			protected void onPostExecute(Void result) {
				mContext.mListDistrict.addAll(rs);
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	public void Purchase() {
		if (mTxtAddress.getText().toString().trim().length() != 0
				&& mTxtPhone.getText().toString().trim().length() != 0
				&& mDistrictListTemp.size() != 0) {
			if (mContext.mOrder == null) {
				mContext.mOrder = new Order();
			}

			if (mContext.mBuyNowOrder == null) {
				mContext.mBuyNowOrder = new Order();
			}

			final Order newOrder = (isBuyNow) ? mContext.mBuyNowOrder
					: mContext.mOrder;

			newOrder.Address = mTxtAddress.getText().toString();
			newOrder.City = mCityListString.get(mSpinCity
					.getSelectedItemPosition());
			newOrder.State = mDistrictListString.get(mSpinDistrict
					.getSelectedItemPosition());
			newOrder.Phone = mTxtPhone.getText().toString();
			newOrder.Memo = mTxtMemo.getText().toString();

			newOrder.ShippingFee = mDistrictListTemp.get(mSpinDistrict
					.getSelectedItemPosition()).Ship;

			mContext.AddPreference("Address", mTxtAddress.getText().toString());
			mContext.AddPreferenceInt("City",
					mSpinCity.getSelectedItemPosition());
			mContext.AddPreferenceInt("District",
					mSpinDistrict.getSelectedItemPosition());
			mContext.AddPreference("Phone", mTxtPhone.getText().toString());
			new OkCancelWarnningDialog(mContext, getContext().getString(
					R.string.areyousure)) {
				public void onOk() {
					new CallServiceTask() {
						private int rs = 0;

						public void work() {
							try {
								rs = service
										.newOrder(
												mContext.mUser.Id,
												newOrder.Address,
												newOrder.City,
												newOrder.State,
												newOrder.Phone,
												1,
												0,
												newOrder.ShippingFee,
												newOrder.Memo,
												mContext.ConvertToJson(newOrder.ListDetail));
							} catch (IOException e) {
							} catch (XmlPullParserException e) {
							}
						};

						protected void onPostExecute(Void result) {
							if (rs < 1) {
								if (!mContext.isConnectionErrorShow) {
									mContext.isConnectionErrorShow = true;
									new ConnectionErrorDialog(mContext) {
										public void TryAgain() {
											Purchase();
										};
									}.show();
								}
								return;
							} else {
								Toast.makeText(
										mContext,
										mContext.getString(R.string.ordersuccessful),
										Toast.LENGTH_SHORT).show();
								if (isBuyNow)
									mContext.mBuyNowOrder = new Order();
								else
									mContext.mOrder = new Order();
								mDialog.dismiss();
							}
						};
					}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
					;
				};
			}.show();
		} else {
			mTxtWarn.setText(mContext.getString(R.string.shippingwarn));
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ship_btnContinue:
			Purchase();
			break;
		case R.id.ship_btnCancel:
			this.dismiss();
			break;
		}
	}

}
